package com.lxy.demo.service;

import com.lxy.demo.entity.LoginUser;
import com.lxy.demo.entity.User;
import com.lxy.demo.utils.JwtUtil;
import com.lxy.demo.utils.RedisCache;
import com.lxy.demo.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    //注入AuthenticationManager的实例对象
    @Autowired(required = false)
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;



    @Override
    public ResponseResult login(User user) {
        //1.通过AuthenticationManager进行认证
        UsernamePasswordAuthenticationToken authToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        //authenticate: 表示认证信息的对象
        Authentication authenticate = authenticationManager.authenticate(authToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录认证失败！");
        }

        //2.获取Userid，生成token，返回到前端
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long id = loginUser.getUser().getId();
        String token = JwtUtil.createJWT(String.valueOf(id));


        //3.把用户信息保存到redis中
        redisCache.setCacheObject("login:"+id,loginUser);
        Map<String,String> map = new HashMap<>();
        map.put("data",token);
        return new ResponseResult(200,"登录成功！",map);
    }

    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中存放的认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
        redisCache.deleteObject("login:"+id);
        return new ResponseResult(200,"退出成功");
    }

}
